package com.bocloud.cmp.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.bocloud.cmp.dao.RegionDao;
import com.bocloud.cmp.entity.resource.Region;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.database.core.BasicDao;

/**
 * 区域管理DAO接口实现
 * 
 * @author dongkai
 *
 */
@Repository("regionDao")
public class RegionDaoImpl extends BasicDao implements RegionDao {

	@Override
	public List<Region> list(Long vendorId) throws Exception {
		String sql = "select * from region where vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
		List<Object> list = this.queryForList(sql, params, Region.class);
		List<Region> regions = new ArrayList<>();
		for (Object obj : list) {
			Region region = (Region) obj;
			regions.add(region);
		}
		return regions;
	}

	@Override
	public Region save(Region region) throws Exception {
		return (Region) this.saveEntity(region);
	}

	@Override
	public Region query(Long id) throws Exception {
		String sql = "select * from region where id = :id";
		Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
		List<Object> list = this.queryForList(sql, params, Region.class);
		if (list.isEmpty()) {
			return null;
		}
		return (Region) list.get(0);
	}

	@Override
	public boolean modify(Region region) throws Exception {
		return this.updateEntity(region);
	}

	@Override
	public boolean delete(Long id) throws Exception {
		String sql = "delete from region where id = :id";
		Map<String, Object> params = MapTools.simpleMap(Common.ID, id);
		return this.update(sql, params) > 0;
	}

	@Override
	public Region getByRegionId(String regionId, Long vendorId) throws Exception {
		String sql = "select * from region where region_id = :regionId and vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap("regionId", regionId);
		params.put("vendorId", vendorId);
		List<Object> list = this.queryForList(sql, params, Region.class);
		if (list.isEmpty()) {
			return null;
		}
		return (Region) list.get(0);
	}

	@Override
	public boolean deleteByVid(Long vendorId) throws Exception {
		String sql = "delete from region where vendor_id = :vendorId";
		Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
		return this.update(sql, params) > 0;
	}

	@Override
	public boolean update(Region region) throws Exception {
		String sql = "update region set name = :name ,code = :code ,vendor_id = :vendorId where id = :id";
		Map<String, Object> params = MapTools.simpleMap("name", region.getName());
		params.put("vendorId", region.getVendorId());
		params.put("code", region.getCode());
		params.put("id", region.getId());
		return this.update(sql, params) > 0;
	}

}
